/*
使用QT实现Tcp协议的服务器和客户端
实现每当客户端断开连接后，服务器就打印“disconnected”。
*/
#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QTcpSocket>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    , m_ptcpserver(new QTcpServer(this))
{
    ui->setupUi(this);

    init_network();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::init_network(){
    if(!m_ptcpserver->listen(QHostAddress("127.0.0.1"), 8099)){
        QMessageBox::warning(this, "listen", "listen fail...");
        exit(1);
    }

    connect(m_ptcpserver, &QTcpServer::newConnection, this, &Widget::new_connection);

    return;
}

void Widget::new_connection(){
    QTcpSocket* ptcpsocket = m_ptcpserver->nextPendingConnection();

    QMessageBox::information(this, "connect", "new connection");

    connect(ptcpsocket, &QTcpSocket::disconnected, this, &Widget::dis_connected);

    return;
}

void Widget::dis_connected(){
    QMessageBox::information(this, "disconnect", "disconnected");

    QTcpSocket* ptcpsocket = (QTcpSocket*)sender();

    ptcpsocket->close();

    return;
}

